import Vue from 'vue';
import Vuex from 'vuex';
import {
	login
} from "@/api/authenticate.js";
Vue.use(Vuex);
export default new Vuex.Store({
	state: {
		// 用户信息
		user_context: uni.getStorageSync('user_context') || '{}',
		// 用户会话id
		cookie: uni.getStorageSync('cookie') || '',
	},
	mutations: {
		// 设置用户信息
		setUserContext(state, user_context) {
			state.user_context = user_context;
		},
		// 设置用户会话
		setCookie(state, cookie) {
			state.cookie = cookie;
		},
	},
	actions: {
		// 登录
		login({
			commit
		}, {
			auto_login,
			params
		}) {
			return new Promise((resolve, reject) => {
				login(params).then(res => {
					if (res.data?.result) {
						let user_context = res.data?.result?.user_context || {};
						let cookie = res.header?.['Set-Cookie'] || '';
						user_context = JSON.stringify(user_context || {});
						if (auto_login) {
							uni.setStorageSync('user_context', user_context);
							uni.setStorageSync('cookie', cookie);
						}
						commit('setUserContext', user_context);
						commit('setCookie', cookie);
						resolve('登录成功!')
					} else {
						reject(res.data?.error?.data?.message || '登录失败!');
					}
				}).catch(err => {
					reject('登录失败!');
				})
			})
		},
		logout({
			commit
		}) {
			let user_context = JSON.stringify({});
			uni.removeStorageSync('user_context');
			uni.removeStorageSync('cookie');
			commit('setUserContext', user_context);
			commit('setCookie', '');
		}
	},
})